import React, { useEffect, useRef, useState } from 'react'
import { Modal, Form, Input, Select } from 'antd';
import { connect } from 'umi';
import _, { cloneDeep } from 'lodash';

function AddUserModal(props: any) {
    // 解构dispatch和公共状态信息
    const { dispatch, regionList, roleList, addOpen, setAddOpen, usersList, setTableLoading } = props;
    // 记录区域选择框的状态数据
    const [regionSelectorData, setRegionSelectorData] = useState(regionList);
    // 记录角色选择框的状态数据
    const [roleSelectorData, setRoleSelectorData] = useState(roleList);
    //新增用户弹出框确认，异步操作时的加载
    const [addConfirmLoading, setAddConfirmLoading] = useState(false);
    //对表单数据域进行交互
    const [form] = Form.useForm();
    // 记录状态，控制region的选择框是否禁用
    const [isRegionSelect, setIsRegionSelect] = useState(false);
    // 从localStorage中获取个人信息区域和角色编码
    const { roleId, region } = JSON.parse(localStorage.getItem('token') as string)[0];
    //订阅信息，通知redux中reducer获取或处理数据
    // 获取区域下拉框的数据
    useEffect(() => {
        if ((regionList as Array<any>).length === 0) {
            dispatch({
                type: 'StandBox/getRegionList',
                payload: {
                }
            })
        }
        else {
            let tempRegionData: Array<any> = _.cloneDeep(regionList);
            tempRegionData = adjustData(tempRegionData, 'label', 'title')
            switch (roleId) {
                case 1:
                    setRegionSelectorData(tempRegionData);
                    break;
                case 2:
                    tempRegionData = _.cloneDeep(tempRegionData).map(item => {
                        if (item.label !== region) {
                            item.disabled = true
                        }
                        return item
                    })
                    setRegionSelectorData(tempRegionData);
                    break;
                default:
                    tempRegionData = tempRegionData.map(item => {
                        item.disabled = true
                        return item
                    })
                    setRegionSelectorData(tempRegionData);
                    break;
            }

        }
    }, [regionList])
    //获取角色下拉框的数据
    useEffect(() => {
        if ((roleList as Array<any>).length === 0) {
            dispatch({
                type: 'StandBox/getRoleList',
                payload: {
                }
            })
        }
        else {
            let tempRoleData: Array<any> = _.cloneDeep(roleList);
            tempRoleData = adjustData(tempRoleData, 'label', 'roleName');
            tempRoleData = adjustData(tempRoleData, 'value', 'roleType');
            switch (roleId) {
                case 1:
                    setRoleSelectorData(tempRoleData);
                    break;
                case 2:
                    tempRoleData = _.cloneDeep(tempRoleData).map(item => {
                        if (item.label === '超级管理员'||item.label === '区域管理员') {
                            item.disabled = true;
                        }
                        return item
                    })
                    setRoleSelectorData(tempRoleData);
                    break;
                default:
                    tempRoleData = _.cloneDeep(tempRoleData).map(item => {
                        item.disabled = true;
                        return item
                    })
                    setRoleSelectorData(tempRoleData);
                    break;
            }

        }
    }, [roleList])

    // 调整数据，使其符合selector,递归,AddProp待添加的属性,
    const adjustData = (regionData: Array<any>, AddProp: string, copyProp: string) => {
        return regionData.map((item: any) => {
            item[AddProp] = item[copyProp];
            if (item?.children?.length > 0) {
                item.children = adjustData(item?.children, AddProp, copyProp);
            }
            return item
        })
    }
    // 添加用户对话框，确定的点击事件
    const handleAddOk = () => {
        setAddConfirmLoading(true);
        setTableLoading(true);
        form.validateFields()
            .then((values) => {
                const completeItem = _.cloneDeep(values);
                completeItem.roleState = true;
                completeItem.default = false;
                console.log(completeItem);
                dispatch({
                    type: 'StandBox/addUsersList',
                    payload: {
                        setAddConfirmLoading,
                        setAddRoleOpen: setAddOpen,
                        resetFields: form.resetFields,
                        usersItem: completeItem,
                        users: usersList,
                        setLoading: setTableLoading
                    }
                })
            })
            .catch((info) => {
                setAddConfirmLoading(false);
                console.log('错误信息:', info);
            });
    }
    // 添加用户对话框，取消的点击事件
    const handleAddCancel = () => {
        setAddOpen(false);
    }

    //区域选择器选择发生改变时执行的回调语句
    const handleRegionSelectorChange = (value: string) => {
        console.log(`selected ${value}`);
    };
    //角色选择器选择发生改变时执行的回调语句
    const handleRoleSelectorChange = (value: number) => {
        if (value === 1) {
            setIsRegionSelect(true);
            form.setFieldsValue({ region: '' });
        }
        else {
            setIsRegionSelect(false);
        }
    };
    return (
        <>
            {/* 添加角色的对话框 */}
            <Modal
                title={`添加用户`}
                open={addOpen}
                onOk={() => { handleAddOk() }}
                confirmLoading={addConfirmLoading}
                onCancel={handleAddCancel}
                okText='确定'
                cancelText='取消'
            >
                <Form
                    name="basic"
                    layout='vertical'
                    initialValues={{ region: '亚洲', roleId: 3 }}
                    autoComplete="off"
                    form={form}
                >
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[{ required: true, message: '请输入用户名！' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[{ required: true, message: '请输入密码！' }]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item
                        label="区域"
                        name="region"
                        rules={[{ required: !isRegionSelect, message: '请选择对应的区域！' }]}
                    >
                        <Select
                            disabled={isRegionSelect}
                            onChange={handleRegionSelectorChange}
                            options={regionSelectorData}
                        />
                    </Form.Item>
                    <Form.Item
                        label="角色"
                        name="roleId"
                        rules={[{ required: true, message: '请选择对应的角色！' }]}
                    >
                        <Select
                            onChange={handleRoleSelectorChange}
                            options={roleSelectorData}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}
const mapStateToProps = (state: any) => {
    return {
        regionList: state.StandBox.regionList,
        roleList: state.StandBox.roleList,
        usersList: state.StandBox.usersList
    }
}
export default connect(mapStateToProps)(AddUserModal)